<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class BackgroundController extends Controller
{
    /**
     * @return string
     */
    public function getBackgroundList()
    {
       // var_dump($_SERVER);
        try{
            $backgrounds =  DB::table('background')->orderBy('id','desc')->Paginate(10);

            return view('Admin/backgroundimglist')->with('backgrounds', $backgrounds);
        }
        catch(\Exception $exception)
        {
            $info =  $exception->getMessage().'failed line:'.$exception->getLine().'failed string:'.$exception->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
        }
    }

    public function addBackground(Request $request)
    {
        //var_dump($request);
        try
        {
            if ( $request->isMethod('post') )
            {
                $data = $request->all();
                $dataArray = [];
                $dataArray['page'] = $data['background_page'];
                $dataArray['description'] = $data['background_description'];

                $path = $this->doUpload($data['background_img']);
                if ( $path === null )
                {
                    return json_encode(['status'=>500, 'msg'=>'upload file failed','data' => null]);
                }


                $dataArray['url'] = $path['path'];

                $result = DB::table('background')->insert($dataArray);
                if ($result)
                {
                    return redirect('admin/getBackgroundList');
                    //return json_encode(['status'=>200, 'msg'=>'add success','data' => $dataArray]);
                }
                else{
                    return json_encode(['status'=>500, 'msg'=>'add failed','data' => $dataArray]);
                }
                //var_dump($dataArray);
            }
            else
            {
                return json_encode(['status'=>500, 'msg'=>'is not post request','data' => null]);
            }
        }
        catch (\Exception $exception)
        {
            $info =  $exception->getMessage().'failed line:'.$exception->getLine().'failed string:'.$exception->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
        }
    }

    public function deleteBackground()
    {

    }

    public function updateBackground(Request $request)
    {
        try
        {
            if ( $request->isMethod('post') )
            {
                $data = $request->all();
                $dataArray = [];
                $id = $data['background_id'];
//                $dataArray['page'] = $data['background_page'];
//                $dataArray['description'] = $data['background_description'];

                if ( isset($data['background_img']) && $data['background_img'] !== null)
                {
                    $path = $this->doUpload($data['background_img']);
                    if ( $path === null )
                    {
                        return json_encode(['status'=>500, 'msg'=>'upload file failed','data' => null]);
                    }
                    $dataArray['url'] = $path['path'];

                    $result = DB::table('background')->where('id','=',$id)->update($dataArray);
                    if ($result)
                    {

                        return redirect('admin/getBackgroundList');

                        //return json_encode(['status'=>200, 'msg'=>'update success','data' => $dataArray]);
                    }
                    else{
                        return json_encode(['status'=>500, 'msg'=>'update failed','data' => null]);
                    }
                }
                else
                {

                    return redirect('admin/getBackgroundList');
                        //return json_encode(['status'=>200, 'msg'=>'update success','data' => $dataArray]);
                }
            }
            else
            {
                return json_encode(['status'=>500, 'msg'=>'is not post request','data' => null]);
            }
        }
        catch (\Exception $exception)
        {
            $info =  $exception->getMessage().'failed line:'.$exception->getLine().'failed string:'.$exception->getTraceAsString();
            return json_encode(['msg'=>0,'data' => $info]);
        }
    }

    private function doUpload($file){
        if ($file->isValid()) {
            // 获取文件相关信息
            //$originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            //$type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
            // 使用我们新建的uploads本地存储空间（目录）
            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
            if(true == $bool){
                $SQLFileName['path'] = 'uploads/'.$filename;
                array_push($SQLFileName,$ext);
                return $SQLFileName;
            }
            else{
                return null;
            }
        }
        else{
            return null;
        }
    }
}
